<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/6
 * Time: 9:27
 */

namespace app\api\controller\product;

use app\api\model\ProductCategoryRelation;
use app\api\model\ProductGroupRelation;
use app\api\model\ProductOrder;
use app\api\model\ProductOrderRelation;
use app\api\model\ProductReview;
use app\api\model\Shop;
use app\api\model\User;
use app\common\controller\zsPayController;
use app\common\model\ProductOrderSpell;
use app\lib\exception\FailedException;
use app\lib\exception\NotFoundException;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use app\Validate\SortTypeValidate;
use think\Controller;
use think\Db;
use think\Request;


class Product extends Controller
{
    /**
     * 获取商品列表  PC->热销商品列表,首页,线上商家-店铺详情,普通商品列表
     * @param Request $request
     * @throws \app\lib\exception\ParameterException
     */
    public function commonProduct(Request $request){
        (new PageMustValidate())->goCheck();
        (new SortTypeValidate())->goCheck();
        $post = $request->post();
        $where=[
            ['a.is_publish','eq',2],
            ['b.type','eq',1],
            ['c.status','eq',2],
            ['c.use_status','eq',1],
        ];
        $where = addWhere($post,['uid'=>''],$where,1,"a.");
        if(isset($post['product_name'])&&!empty($post['product_name'])){ //如果有商品名称搜索 就是搜索商品名称和国际编码搜索
            $where[] = ['a.product_name|a.international_code|d.position_code','like',"%".$post['product_name']."%"];
        }
        if(isset($post['category_id']) && !empty($post['category_id']) && $post['category_id'] != "undefined"){
            $list = (new ProductCategoryRelation())->selectListByColumn([['category_id','eq',$post['category_id']]],"product_id","product_id desc");
            $where[] = ['a.id','in',$list];
        }
        if(isset($post['group_id'])&&!empty($post['group_id'])){
            $list = (new ProductGroupRelation())->selectListByColumn([['group_id','eq',$post['group_id']]],"product_id",'product_id desc');
            $where[] = ['a.id','in',$list];
        }
        //根据某个店铺进行查询
        if(isset($post['shop_id'])&&!empty($post['shop_id'])){
            $where[] = ['c.id','eq',$post['shop_id']];
        }
        //区分线上商家1/ 品牌店2/ 贸易商3
        if(isset($post['shop_type'])&&!empty($post['shop_type'])){
            $where[] = ['c.type','eq',$post['shop_type']];
        }
        $field = "a.id,a.cover_img,a.product_name,a.sales_actual_number,b.price,b.min_number,b.id price_id,c.id shop_id,c.type,d.position_code,d.id as hall_id";
        $sort = "";
        switch ($post['sortType']){
            case 1: //销量排序
                $sort = "a.sales_actual_number desc,a.id desc";
                break;
            case 2://新品排序
                $sort = "a.create_time desc,a.id desc";
                break;
            case 3://价格降序
                $sort = "b.price desc,a.id desc";
                break;
            case 4://价格升序
                $sort = "b.price,a.id desc";
                break;
        }
        $dataList = (new \app\api\model\Product())
            ->alias("a")
            ->join("om_product_price b","a.id = b.product_id and b.delete_time is null","left")
            ->join("om_shop c","a.uid = c.id","left")
            ->join("om_trade_hall d","d.product_id = a.id AND d.delete_time IS NULL","left")
            ->field($field)
            ->where($where)
            ->order($sort)
            ->paginate($post['page_number'], false, [
                'page' => $post['page']]);
        $dataList=$dataList->toArray();
        $data = $dataList['data'];
        foreach ($data as $key=>$value){
            $data[$key]['cover_img'] = imgUrlToAbsolute($value['cover_img']);
            if($value['hall_id'] > 0){
                continue;
            }
            //增加hall_id字段，如果有则随机取一条，没有则为0
            $data[$key]['hall_id'] = 0;
            $hallModel = (new \app\api\model\TradeHall())->where([["product_id","eq",$value["id"]]])->limit(1)->find();
            if(isset($hallModel)){
                $data[$key]['hall_id'] = $hallModel["id"];
            }
        }

        $returnList = [
            'count'=>$dataList['total'],
            'data'=>$data
        ];
        return writeJson(200,$returnList);
    }

    /**
     * @param Request $request
     * @throws \app\lib\exception\ParameterException
     */
    public function hotProduct(Request $request){
        (new PageMustValidate())->goCheck();
        (new SortTypeValidate())->goCheck();
        $post = $request->post();
        $where=[
            ['a.is_publish','eq',2],
            ['c.status','eq',2],
            ['c.use_status','eq',1],
        ];
        $where = addWhere($post,['uid'=>''],$where,1,"a.");
        if(isset($post['product_name'])){ //如果有商品名称搜索 就是搜索商品名称和国际编码搜索
            $where[] = ['a.product_name|a.international_code','like',"%".$post['product_name']."%"];
        }
        if(isset($post['category_id'])&&!empty($post['category_id'])){
            $list = (new ProductCategoryRelation())->selectListByColumn([['category_id','eq',$post['category_id']]],"product_id","product_id desc");
            $where[] = ['a.id','in',$list];
        }
        if(isset($post['group_id'])&&!empty($post['group_id'])){
            $list = (new ProductGroupRelation())->selectListByColumn([['group_id','eq',$post['group_id']]],"product_id",'product_id desc');
            $where[] = ['a.id','in',$list];
        }
        $field = "a.id,a.cover_img,a.product_name,a.sales_actual_number,b.price,b.min_number,c.type";
        $sort = "a.sales_actual_number desc";
        $dataList = (new \app\api\model\Product())
            ->alias("a")
            ->join("om_product_price b","a.id = b.product_id and b.type = 1 delete_time","right")
            ->join("om_shop c","a.uid = c.id","right")
            ->field($field)
            ->where($where)
            ->order($sort)
            ->paginate($post['page_number'], false, [
                'page' => $post['page']]);
        $dataList=$dataList->toArray();
        $data = $dataList['data'];
        foreach ($data as $key=>$value){
            $data[$key]['cover_img'] = imgUrlToAbsolute($value['cover_img']);
        }
        $returnList = [
            'count'=>$dataList['total'],
            'data'=>$data
        ];
        return writeJson(200,$returnList);
    }

    /**
     * 商品详情
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function productDetail(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $where=[
            ['id','eq',$post['id']],
            ['is_publish','eq',2]
        ];
        $product = (new \app\api\model\Product())->findOneWith("product_price,product_spec,product_spec_item",$where,"id,uid,product_name,cover_img,img_path,description,product_price_one,market_price,sku_remark");
        if(!$product){
            throw new NotFoundException(['msg'=>"产品不存在"]);
        }

        //+浏览量
        $res = (new \app\api\model\Product())->where("id",$post['id'])->setInc("hot_number");
        if(!$res){
            throw new FailedException(['msg'=>'浏览量添加失败']);
        }
        $shop   =  (new Shop())->findOne([['id','eq',$product['uid']],['status','eq',2],['use_status','eq',1]],"id,name,type,phone");
        if(!$shop){
            throw new NotFoundException(['msg'=>"商家不存在或者被封停"]);
        }
        $product = $product->toArray();
        $product['description'] = html_entity_decode($product['description']);
        $spec = arrayLevel($product['product_spec'],$product['product_spec_item'],"spec_id");
        $spec = array_values($spec);
        $sku  = (new \app\api\model\Product())->getSkuStock($product['id'],$shop['type'],$product['uid']);
        $product["product_stock"] = (new \app\api\model\Product())->getProductStock($product['id'],$shop['type'],$product['uid']);
        $price = $product['product_price'];
        unset($product['product_price']);
        unset($product['product_spec']);
        unset($product['product_spec_item']);
        $product['cover_img'] = imgUrlToAbsolute($product['cover_img']);
        $product['img_path'] = serializeMysql($product['img_path'],1);
        $product['url'] = 'http://www.globaltc.cn/#/details?id='.$post['id'];
        //$product['content_url'] = 'http://www.globaltc.cn/#/textpage?id='.$post['id'].'&type=2';
        $product['content_url'] = 'http://wx.youywt.com/index/index/ceshilink/id/'.$post['id'].'/type/2';
        $product["description"] = (new \app\api\model\Product())->getProductDescription($product["id"]);
        foreach ($product['img_path'] as &$value){
            $value = imgUrlToAbsolute($value);
        }
        $review = (new ProductReview())->findOneWith("user",[['product_id','eq',$post['id']]],"*","id desc");
        if(!$review){
            $review = [];
        }else{
            $review["phone"] = substr_replace($review["phone"],'****',3,4);
        }

        $user_type = 1; //默认免费会员
        if(isset($post["user_id"])){
            //获取会员组别
            $user_type = (new User())->getUserType($post["user_id"]);
        }

        $returnList = [
            'product'=>$product,
            'shop'   =>$shop,
            'spec'   =>$spec,
            'sku'    =>$sku,
            'price'  =>$price,
            'review' =>$review,
            'user_type' => $user_type
            //'url'=>'http://www.globaltc.cn/#/assembledetail?id='.$post['id']
        ];
        return writeJson(200,$returnList);
    }

    /**
     * 查看商品的全部评价
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function productAllReview(Request $request){
        (new IdMustPositive())->goCheck();
        (new PageMustValidate())->goCheck();
        $post =$request->post();
        //1 普通商城 2 秒杀商城 3拼团商城  如果不传则做兼容处理
        if(!isset($post['type'])){ $post['type'] = 1; }

        $where=[
            ['id','eq',$post['id']],
            ['is_publish','eq',2]
        ];
        $count = (new \app\api\model\Product())->getCount($where);
        if($count==0){
            throw new NotFoundException(['msg'=>'商品不存在']);
        }
        $where = [];
        $where[] = ['product_id','eq',$post['id']];
        $where[] = ['type','eq',$post['type']];
        $where['page'] = $post['page'];
        $dataList = (new ProductReview())->wechatListTotalWith("user",$where,"*","id desc",$post['page_number']);
        foreach ($dataList["data"] as $k=>$v){
            $dataList["data"][$k]["phone"] = substr_replace($v["phone"], '****',3, 4);
        }
        return writeJson(200,$dataList);
    }

    /**
     * 根据国际编码获取商品信息
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductByInter(Request $request){
        $post =$request->post();
        $this->log($post);
        if(!isset($post["international_code"])){throw new NotFoundException(['msg'=>'请输入国际编码']); }

        $ProductModel = (new \app\api\model\Product());
        $count = $ProductModel->alias("a")
            ->join("om_shop c","c.id = a.uid")
            ->where('international_code','eq',$post["international_code"])
            ->where("c.type","eq",3)  //只允许搜索到贸易商商品
            ->count();
        if($count==0){throw  new NotFoundException(['msg'=>'商品不存在']); }

        $data = $ProductModel->alias("a")
            ->field('a.id,a.international_code,a.product_name,b.id as hall_id,b.position_code')
            ->join("om_shop c","c.id = a.uid")
            ->join("om_trade_hall b","a.id = b.product_id","left")
            ->where('international_code','eq',$post["international_code"])
            ->where("c.type","eq",3)  //只允许搜索到贸易商商品
            ->orderRand()
            ->limit(0,1)
            ->select()->toArray();

        //ID转换为字符串格式
        $data[0]["id"] = $data[0]["id"]."";
        return writeJson(200,$data);
    }

    /**
     * 获取商品详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductDescription(Request $request){
        (new IdMustPositive())->goCheck();
        $get = $request->get();
        $productService = new \app\api\model\Product();
        $product = $productService->field("description")->where(["id"=>$get["id"]])->find();
        return writeJson(200,$product);
    }
}